using System.IO;
using System.Net;
using System.Runtime.Serialization;
using System.IO;

public class IPAddressConverter : JsonConverter<IPAddress>
{
    public override void WriteJson(JsonWriter writer, IPAddress value, JsonSerializer serializer)
    {
        writer.WriteValue(value?.ToString());
    }

    public override IPAddress ReadJson(JsonReader reader, Type objectType, IPAddress existingValue, bool hasExistingValue, JsonSerializer serializer)
    {
        if (reader.Value == null) return null;
        return IPAddress.Parse(reader.Value.ToString());
    }
}

public static class ConfigManager
{
    private static readonly string configPath = "config.json";
    private static bool _serializationEnabled = true;

    public static bool SerializationEnabled 
    {
        get => _serializationEnabled;
        set => _serializationEnabled = value;
    }

    public static void SaveConfig(object config)
    {
        if (!_serializationEnabled) return;
        
        var serializer = new DataContractSerializer(config.GetType());
        using (var writer = File.CreateText(configPath))
        {
            serializer.WriteObject(writer.BaseStream, config);
        }
    }

    public static T LoadConfig<T>() where T : new()
    {
        if (!_serializationEnabled || !File.Exists(configPath))
            return new T();

        try
        {
            var serializer = new DataContractSerializer(typeof(T));
            using (var stream = File.OpenRead(configPath))
            {
                return (T)serializer.ReadObject(stream);
            }
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine($"反序列化错误: {ex.Message}");
            return new T();
        }
    }
}